<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="任务类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择任务类型" clearable>
          <el-option v-for="dict in dict.type.task_type" :key="dict.value" :label="dict.label" :value="dict.value"
            v-if="dict.value !== '1'" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable>
          <el-option v-for="dict in dict.type.task_status" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" v-if="dict.value === '2' || dict.value === '3'" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker v-model="daterangeStartTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="daterangeEndTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['exam:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['exam:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['exam:task:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['exam:task:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键，任务ID" align="center" prop="id" /> -->
      <el-table-column label="任务名称" align="center" prop="name" />
      <el-table-column label="任务类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- 任务状态 -->
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="任务耗时（分钟）" align="center" prop="taskTime" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:task:edit']" :disabled="scope.row.taskStatus === 3">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['exam:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="绑定试卷" prop="taskExamPaperId" v-if="!isDaily">
          <el-select v-model="form.taskExamPaperId" filterable placeholder="请选择试卷" @change="handlePaperChange">
            <el-option v-for="item in paperList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择任务类型" @change="handleTaskTypeChange">
            <el-option v-for="dict in dict.type.task_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)" v-if="dict.value !== '1'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss" placeholder="请选择任务开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss" placeholder="请选择任务结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="限定任务耗时" prop="taskTime">
          <!-- <el-input v-model="form.taskTime" placeholder="限定任务耗时" /> -->
          <div style="display: flex; align-items: center;">
            <el-input-number v-model="form.taskTime" :step="10" style="flex: 1;" />
            <span style="margin-left: 8px;">分钟</span>
          </div>
        </el-form-item>

        <el-form-item label="题型配置" v-if="isDaily">
          <div v-for="item in questionTypeConfig" :key="item.type" style="margin-bottom: 15px;">
            <div style="display: flex; align-items: center; margin-bottom: 8px;">
              <span style="width: 80px;">{{ item.label }}</span>
              <el-select v-model="item.category" placeholder="选择题目分类" style="width: 150px; margin-right: 10px;">
                <el-option label="不限" :value="0">
                </el-option>
                <el-option v-for="dict in dict.type.job_category" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)">
                </el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center;">
              <span style="width: 80px;"></span>
              <el-slider v-model="item.count" :min="0" :max="5" :step="1" :format-tooltip="formatTooltip"
                style="flex: 1; margin: 0 10px;" show-stops @change="handleCountChange">
              </el-slider>
              <span style="width: 35px; text-align: right;">{{ item.count }}题</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/exam/task";
import { listPaper, getPaper, delPaper, addPaper, updatePaper } from "@/api/exam/paper";

export default {
  name: "Task",
  dicts: ['task_type', 'exam_question_type', 'job_category', 'task_status'],
  data() {
    // 自定义校验方法
    const validateQuestionConfig = (rule, value, callback) => {
      if (this.isDaily) {
        const hasQuestions = this.questionTypeConfig.some(item => item.count > 0);
        if (!hasQuestions) {
          callback(new Error('每日一练必须配置至少一种题型'));
        }
      }
      callback();
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 任务试卷ID，关联 t_task_exam_paper 表主键时间范围
      daterangeStartTime: [],
      // 任务试卷ID，关联 t_task_exam_paper 表主键时间范围
      daterangeEndTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        taskStatus: null,
        params: {}
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "任务类型不能为空", trigger: "change" },
          { validator: validateQuestionConfig, trigger: "change" }
        ],
        taskExamPaperId: [
          {
            required: true,
            message: "任务试卷ID不能为空",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (!this.isDaily && !value) {
                callback(new Error("请选择试卷"));
              } else {
                callback();
              }
            }
          }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      },
      paperList: [],
      // 添加题型配置数据
      questionTypeConfig: [],
    };
  },
  created() {
    this.getList();

    this.getPaperList();

    // 初始化题型配置
    this.initQuestionTypeConfig();
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      // 排除每日一练类型(type=1)的任务
      this.queryParams.excludeType = '1';

      if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
        this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0];
        this.queryParams.params["endStartTime"] = this.daterangeStartTime[1];
      }
      if (null != this.daterangeEndTime && '' != this.daterangeEndTime) {
        this.queryParams.params["beginEndTime"] = this.daterangeEndTime[0];
        this.queryParams.params["endEndTime"] = this.daterangeEndTime[1];
      }
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        console.log('任务列表数据', response.rows);
        this.total = response.total;
        this.loading = false;
      });
    },
    getPaperList() {
      const paperQueryParams = {
        pageNum: 1,
        pageSize: 999,
      }
      listPaper(paperQueryParams).then(response => {
        this.paperList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        startTime: null,
        endTime: null,
        taskTime: null,
        taskExamPaperId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deleted: null,
        questionConfig: null // 添加题型配置字段
      };
      this.resetForm("form");
      this.initQuestionTypeConfig();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartTime = [];
      this.daterangeEndTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        // 如果有题型配置数据，需要解析JSON字符串
        if (this.form.questionConfig) {
          try {
            const configArray = JSON.parse(this.form.questionConfig);
            this.questionTypeConfig = this.questionTypeConfig.map(item => {
              const config = configArray.find(c => c.questionType === item.type);
              if (config) {
                return {
                  ...item,
                  count: config.questionCount,
                  category: config.categoryId
                };
              }
              return item;
            });
          } catch (e) {
            console.error('解析题型配置失败:', e);
          }
        }
        this.open = true;
        this.title = "修改任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let submitData = { ...this.form };

          if (this.isDaily) {
            // 过滤掉数量为0的配置，并转换为JSON字符串
            submitData.questionConfig = JSON.stringify(
              this.questionTypeConfig
                .filter(item => item.count > 0)
                .map(item => ({
                  questionType: item.type,
                  questionCount: item.count,
                  categoryId: item.category
                }))
            );
            submitData.taskExamPaperId = null;
          }

          if (submitData.id != null) {
            updateTask(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除任务编号为"' + ids + '"的数据项？').then(function () {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exam/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    // 初始化题型配置
    initQuestionTypeConfig() {
      if (this.dict.type.exam_question_type) {
        this.questionTypeConfig = this.dict.type.exam_question_type.map(item => ({
          type: parseInt(item.value),    // 题目类型
          label: item.label,             // 题目类型标签
          count: 0,                      // 题目数量
          category: 0                    // 题目分类，默认0表示不限
        }));
      }
    },
    // 添加格式化提示的方法
    formatTooltip(val) {
      return val + '题';
    },
    // 修改题型数量变化的处理方法
    handleCountChange() {
      // 当题型数量发生变化时，触发表单校验
      this.$refs.form.validateField('type');
    },
    handlePaperChange(val) {
      const selectedPaper = this.paperList.find(item => item.id === val);
      if (selectedPaper) {
        this.form.name = selectedPaper.name;
        this.form.taskTime = selectedPaper.suggestTime;
      }
    },
    handleTaskTypeChange(type) {
      const now = new Date();
      let start, end;

      if (type === 3) { // 月考
        // 本月第一天
        start = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
        // 本月最后一天
        end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);

      } else if (type === 2) { // 周考
        const day = now.getDay() || 7; // 周日改成7
        start = new Date(now);
        start.setDate(now.getDate() - day + 1); // 本周周一
        start.setHours(0, 0, 0, 0);

        end = new Date(start);
        end.setDate(start.getDate() + 6); // 本周周日
        end.setHours(23, 59, 59, 999);

      } else if (type === 4) { // 季考
        const quarter = Math.floor(now.getMonth() / 3);
        start = new Date(now.getFullYear(), quarter * 3, 1, 0, 0, 0);

        end = new Date(now.getFullYear(), quarter * 3 + 3, 0, 23, 59, 59);
      }else if (type === 5) { // 清除
        this.form.startTime = '';
        this.form.endTime = '';
        return;
      }

      if (start && end) {
        // 格式化成 yyyy-MM-dd HH:mm:ss
        const format = (d) => {
          const pad = (n) => n.toString().padStart(2, '0');
          return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
        };
        this.form.startTime = format(start);
        this.form.endTime = format(end);
      }
    },
  },
  computed: {
    isDaily() {
      return this.form.type === 1; // 假设1代表每日任务，请根据实际的字典值调整
    }
  },
  watch: {
    // 监听题型配置的变化
    questionTypeConfig: {
      handler(val) {
        // 当配置发生变化时，如果是每日任务，则触发校验
        if (this.isDaily) {
          this.$nextTick(() => {
            this.$refs.form.validateField('type');
          });
        }
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.el-slider {
  margin-top: 8px;
}

/* 调整滑块停止点的大小 */
:deep(.el-slider__stop) {
  width: 4px;
  height: 4px;
}

/* 调整滑块按钮的大小 */
:deep(.el-slider__button) {
  width: 12px;
  height: 12px;
}

/* 调整滑块轨道的度 */
:deep(.el-slider__runway) {
  height: 4px;
}

:deep(.el-slider__bar) {
  height: 4px;
}
</style>
